package com.blq.web.CustomerRepair.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blq.api.domain.MaterialAfter;
import com.blq.api.domain.MaterialBefore;
import com.blq.api.mapper.EvaluationBackupMapper;
import com.blq.api.mapper.MaterialAfterMapper;
import com.blq.api.mapper.MaterialBeforeMapper;
import com.blq.common.core.domain.entity.SysDept;
import com.blq.common.core.domain.entity.SysUser;
import com.blq.common.exception.ServiceException;
import com.blq.common.utils.ResultMsg;
import com.blq.common.utils.StringUtils;
import com.blq.api.domain.EvaluationBackup;
import com.blq.system.domain.SysOss;
import com.blq.system.domain.SysPost;
import com.blq.system.domain.SysUserPost;
import com.blq.system.domain.SysUserRole;
import com.blq.system.mapper.*;
import com.blq.system.service.ISysDeptService;
import com.blq.system.service.ISysPostService;
import com.blq.system.service.ISysUserService;
import com.blq.web.CustomerRepair.domain.CustomerRepair;
import com.blq.web.CustomerRepair.domain.vo.CustomerRepairVo;
import com.blq.web.CustomerRepair.mapper.CustomerRepairMapper;
import com.blq.web.CustomerRepair.service.ICustomerRepairService;
import com.blq.web.PayoutInformation.domain.MaterialInfo;
import com.blq.web.PayoutInformation.domain.PayoutInformation;
import com.blq.web.PayoutInformation.mapper.MaterialInfoMapper;
import com.blq.web.PayoutInformation.mapper.PayoutInformationMapper;
import com.blq.web.customerMode.entiy.*;
import com.blq.web.customerMode.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author BLQ
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class ComerController {

    @Autowired
    private PayoutInformationMapper payoutInformationMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysNoticeMapper sysNoticeMapper;
    @Autowired
    private EvaluationBackupMapper evaluationBackupMapper;
    @Autowired
    private ICustomerRepairService iCustomerRepairService;
    @Autowired
    private MaterialAfterMapper materialAfterMapper;
    @Autowired
    private MaterialBeforeMapper materialBeforeMapper;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysPostService iSysPostService;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private InvestigationMapper investigationMapper;

    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private EvaluationMapper evaluationMapper;

    @Autowired
    private SysDeptMapper baseMapper;

    @Autowired
    private SysUserMapper baseMapperUser;
    @Autowired
    private CustomerRepairMapper customerRepairMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;
    @Autowired
    private SysOssMapper sysOssMapper;

    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private void handleMessage(String orderId, String userId) {
        if (StringUtils.isBlank(userId)) {
            return;
        }
        String date = time.format(new Date());
        if (customerRepairMapper.selectUserIsOrderKh(userId,orderId) > 0) {
            sysNoticeMapper.updateBycustomerKeyUpdateUser(orderId,date);
        }
        if (customerRepairMapper.selectUserIsOrderSf(userId,orderId) > 0) {
            sysNoticeMapper.updateBycustomerKeyUpdateWorker(orderId,date);
        }
        if (customerRepairMapper.selectUserIsOrderSh(userId,orderId) > 0) {
            sysNoticeMapper.updateBycustomerKeyUpdatePrincipal(orderId,date);
        }
        if (customerRepairMapper.selectUserIsOrderCw(userId,orderId) > 0) {
            sysNoticeMapper.updateBycustomerKeyUpdateFinance(orderId,date);
        }
    }

    /**
     * @Description 接口描述 : app端 待办理处-->点击某个订单
     * @Params * @param null
     * customerKey : 订单id
     * @Return   messagePort
     * @Author xiaw
     * @Date 2022/12/25 0:08
     */
    @GetMapping("EcorsScor")
    public ResultMsg editMessage2(String customerKey,String hasRead,String loginmanId){

        //阅读修改订单阅读状态
        handleMessage(customerKey, loginmanId);
        /*if (!StringUtils.isBlank(hasRead)){

            if (hasRead.equals("true")){
                //判断角色-更改阅读状态
                ArrayList<String> strings = roleJudgment(loginmanId);
                for (String string : strings) {
                    String date = time.format(new Date());
                    //根据工单号和阅读人员修改公告状态
                    if (string.equals("平台客户")) sysNoticeMapper.updateBycustomerKeyUpdateUser(customerKey,date);
                    if (string.equals("分公司财务")) sysNoticeMapper.updateBycustomerKeyUpdateFinance(customerKey,date);
                    if (string.equals("分公司运维部门负责人")) sysNoticeMapper.updateBycustomerKeyUpdatePrincipal(customerKey,date);
                    if (string.equals("分公司施工人员")) sysNoticeMapper.updateBycustomerKeyUpdateWorker(customerKey,date);
                }
            }
        }*/

        CustomerRepairVo customerRepairVo0 = new CustomerRepairVo();
        //第一页
        /**第一-------
         * 标题 : 维修类型
         * 工单编号
         * 发起人 :
         * 联系电话
         * 发起时间
         * 工单状态
         * 地址
         * 问题描述
         */
        //订单详情
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerRepair customerRepair = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>().eq("customer_key", customerKey));
        if (customerRepair != null) {
            SysUser sysUser = getSysUserByUserId(customerRepair.getCustomerId());
            customerRepairVo0.setInitiator(sysUser.getNickName());
            customerRepairVo0.setCustomerName(customerRepair.getCustomerName());
            customerRepairVo0.setCustomerPhone(customerRepair.getCustomerPhone());
            customerRepairVo0.setWorkOrderStatus(customerRepair.getCustomerFlag());
            customerRepairVo0.setCustomerTimer(customerRepair.getCreateTime());
            customerRepairVo0.setAppointmentTime(customerRepair.getCustomerTimer());
            customerRepairVo0.setApplicationMaterial(customerRepair.getCustomerFiles());
            customerRepairVo0.setTurnoverTime(customerRepair.getUpdateTime());
            customerRepairVo0.setLiaison(customerRepair.getLiaison());
            customerRepairVo0.setLiaisonPhone(customerRepair.getLiaisonPhone());
            if(customerRepair.getCompanyId()!=null )customerRepairVo0.setCompanyId(customerRepair.getCompanyId());
            customerRepairVo0.setAssignmentType(customerRepair.getCustomerAuto());
            BeanUtils.copyProperties(customerRepair, customerRepairVo0);
            customerRepairVo0.setReceiveTime(customerRepair.getReceiveTime());
            customerRepairVo0.setProvince(customerRepair.getProvince());
            customerRepairVo0.setCity(customerRepair.getCity());
            customerRepairVo0.setArea(customerRepair.getArea());
            customerRepairVo0.setLon(customerRepair.getLon());
            customerRepairVo0.setLat(customerRepair.getLat());
            customerRepairVo0.setMaterialTime(customerRepair.getMaterialTime());
            //接单人信息
            if (customerRepair.getReceiverMan() != null) {
                Set<String> DepartmentName = new HashSet<>();
                Set<String> getNickName = new HashSet<>();
                Set<String> getPhonenumber = new HashSet<>();
                Set<String> TheUnitToWhichTheOrderBelongs = new HashSet<>();
                String customerPlayer = customerRepair.getReceiverMan();
                String[] split = customerPlayer.split(",");
                for (String s : split) {
                    SysUser sysUser1 = getSysUserByUserId(s);
                    DepartmentName.add(getDepartmentName(sysUser1));
                    getNickName.add(sysUser1.getNickName());
                    getPhonenumber.add(sysUser1.getPhonenumber());
//                    TheUnitToWhichTheOrderBelongs.add(getDeptName(String.valueOf(sysUser1.getDeptId())));
                    TheUnitToWhichTheOrderBelongs.add(getOrgId(s));
                }
                customerRepairVo0.setReceiverId(customerPlayer);
                customerRepairVo0.setDepartment1(DepartmentName.toString().substring(1,DepartmentName.toString().length()-1));
                customerRepairVo0.setReceiver(getNickName.toString().substring(1,getNickName.toString().length()-1));
                customerRepairVo0.setAnswerASingleCall(getPhonenumber.toString().substring(1,getPhonenumber.toString().length()-1));
                customerRepairVo0.setTheUnitToWhichTheOrderBelongs(TheUnitToWhichTheOrderBelongs
                        .toString().substring(1,TheUnitToWhichTheOrderBelongs.toString().length()-1));
            }
            //指派订单人信息
            if (customerRepair.getCustomerDesignate() !=null){
                String customerPlayer = customerRepair.getCustomerDesignate();
                SysUser sysUser1 = getSysUserByUserId(customerPlayer);
                customerRepairVo0.setDesignateDepartment1(getDepartmentName(sysUser1));
                customerRepairVo0.setDesignateReceiver(sysUser1.getNickName());
                customerRepairVo0.setDesignateAnswerASingleCall(sysUser1.getPhonenumber());
//                customerRepairVo0.setDesignateTheUnitToWhichTheOrderBelongs(getDeptName(String.valueOf(sysUser1.getDeptId())));
                customerRepairVo0.setDesignateTheUnitToWhichTheOrderBelongs(getOrgId(customerPlayer));
                customerRepairVo0.setDesignateReceiveTime(customerRepair.getCustomerDesignateTime());
            }
            //转单人信息
            if (!StringUtils.isBlank(customerRepair.getCustomerUnit())){
                String customerUnit = customerRepair.getCustomerUnit();//转单人id
                SysUser transferSolo = getSysUserByUserId(customerUnit);//转单人对象
                //放入
                customerRepairVo0.setToReceiveTime(customerRepair.getCustomerTime());//转单时间
                customerRepairVo0.setToReceiver(transferSolo.getNickName());//转单人名字
                customerRepairVo0.setToAnswerASingleCall(transferSolo.getPhonenumber());//电话
//                customerRepairVo0.setToTheUnitToWhichTheOrderBelongs(getDeptName(String.valueOf(transferSolo.getDeptId())));
                customerRepairVo0.setToTheUnitToWhichTheOrderBelongs(getOrgId(customerUnit));
                customerRepairVo0.setToDepartment1(getDepartmentName(transferSolo));//转单人部门名字
            }
            //提交审核
            Ticket ticketRepair = ticketMapper.selectOne(new QueryWrapper<Ticket>().eq("ticket_repair", customerKey));
            if (ticketRepair != null) {
                if (ticketRepair.getTicketEquip()!=null){
                    customerRepairVo0.setStatus(ticketRepair.getTicketReslover());//审核结果
                    if (ticketRepair.getTicketUser().contains(",")) {
                        //多人
                        String ticketReviewer1 = ticketRepair.getTicketUser();
                        String[] split3 = ticketReviewer1.split(",");
                        LinkedHashSet<String> strings = new LinkedHashSet<>();
                        for (int i = 0; i < split3.length; i++) {
                            String name = split3[i];
                            strings.add(name);
                        }
                        StringBuilder username = new StringBuilder();
                        StringBuilder deptname = new StringBuilder();//部门名字
                        StringBuilder unit = new StringBuilder();
                        StringBuilder phone = new StringBuilder();
                        //部门和单位去重
                        LinkedHashSet<String> highDepartment = new LinkedHashSet<>();
                        LinkedHashSet<String> department = new LinkedHashSet<>();
                        for (String string : strings) {
                            //用户名
                            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("user_id", Long.parseLong(string));
                            SysUser proposer = sysUserMapper.selectOne(queryWrapper);
                            username.append("," + proposer.getNickName());
                            //根据用户,当前部门拼接部门名字
                            String departmentName = getDepartmentName(proposer);
                            department.add(departmentName);
                            //单位
//                            String deptName = getDeptName(String.valueOf(proposer.getDeptId()));
                            String deptName = getOrgId(string);
                            highDepartment.add(deptName);
                            //电话
                            phone.append("," + proposer.getPhonenumber());
                        }
                        department.forEach(a -> deptname.append("," + a));
                        highDepartment.forEach(a -> unit.append("," + a));
                        String substringusername = username.substring(1);
                        String substringdeptname = deptname.substring(1);
                        String substringunit = unit.substring(1);//部门名字
                        String substringphone = phone.substring(1);
                        customerRepairVo0.setApplicantTelephoneNumber(substringphone);
                        customerRepairVo0.setDepartment(substringdeptname);
                        customerRepairVo0.setAffiliatedUnit(substringunit);
                        customerRepairVo0.setProposer(substringusername);

                    } else {//单人
                        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("user_id", Long.parseLong(ticketRepair.getTicketUser()));
                        SysUser proposer = sysUserMapper.selectOne(queryWrapper);
                        customerRepairVo0.setApplicantTelephoneNumber(proposer.getPhonenumber());
                        customerRepairVo0.setDepartment(getDepartmentName(proposer));
//                        customerRepairVo0.setAffiliatedUnit(getDeptName(String.valueOf(proposer.getDeptId())));
                        customerRepairVo0.setAffiliatedUnit(getOrgId(ticketRepair.getTicketUser()));
                        customerRepairVo0.setProposer(proposer.getNickName());
                    }
                    String[] split = ticketRepair.getTicketUser().split(",");
                    long count = Arrays.stream(split).count();
                    customerRepairVo0.setMaintenancePersonnel(String.valueOf(count));
                    BeanUtils.copyProperties(ticketRepair, customerRepairVo0);

                    //审核员
                    if (ticketRepair.getTicketReviewer() != null) {
                        customerRepairVo0.setAssessingOfficer(getSysUserByUserId(ticketRepair.getTicketReviewer()).getNickName());
                        //勘察信息
                        Investigation investigation_repari = investigationMapper.selectOne(new QueryWrapper<Investigation>().eq("investigation_repari", customerKey));
                        if (investigation_repari != null) {
                            BeanUtils.copyProperties(investigation_repari, customerRepairVo0);
                            try {
                                List<MaterialBefore> materialBefores = materialBeforeMapper.selectList(new QueryWrapper<MaterialBefore>()
                                        .eq("material_repari", customerKey).eq("ids",investigation_repari.getInvestigationKey()));
                                if (materialBefores.size()!=0) customerRepairVo0.setMaterialBefore(materialBefores);
                                customerRepairVo0.setInvestigationTime(simpleDateFormat.parse(investigation_repari.getInvestigationTime()));
                                customerRepairVo0.setInvestigationOver(simpleDateFormat.parse(investigation_repari.getInvestigationOver()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                customerRepairVo0.setRemark(ticketRepair.getRemark());
            }
            //上传报价方案
            Quotation quotation_repair = quotationMapper.selectOne(new QueryWrapper<Quotation>().eq("quotation_repair", customerKey));
            if (quotation_repair != null) {
                customerRepairVo0.setQuotationScmorTime(quotation_repair.getCreateTime());
                BeanUtils.copyProperties(quotation_repair, customerRepairVo0);
            }
            //待客户付款
            PayoutInformation payout_key = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", customerKey));
            if (payout_key != null) {
                BeanUtils.copyProperties(payout_key, customerRepairVo0);
                if (payout_key.getPaymentStatus().equals("1"))
                    customerRepairVo0.setCollectionStatus("已付款");
                if (payout_key.getPaymentStatus().equals("0"))
                    customerRepairVo0.setCollectionStatus("未付款");
                customerRepairVo0.setPayoutFromId(payout_key.getPayoutFromId());
                customerRepairVo0.setPayoutFrom(payout_key.getPayoutFrom());
                customerRepairVo0.setConfirmTheTimeOfPayment(payout_key.getConfirmTheTimeOfPayment());
                customerRepairVo0.setPayoutUser(payout_key.getPayoutUser());
                customerRepairVo0.setPayerSPhone(payout_key.getPayoutPhone());
                customerRepairVo0.setPhoneNumberOfTheContact("收款联系人");
                customerRepairVo0.setPayoutPrice(payout_key.getPayoutPrice().toString());

                SysOss sysOss = sysOssMapper.selectById(payout_key.getPayoutCode());
                if (sysOss != null) {
                    customerRepairVo0.setPayoutCode(sysOss.getUrl());
                }
                customerRepairVo0.setConfirmationOfPayer(payout_key.getConfirmationPaymentBy());//确认付款人
                customerRepairVo0.setConfirmTheTimeOfPayment(payout_key.getConfirmTheTimeOfPayment());//确认付款时间
                customerRepairVo0.setConfirmTheRecipient(payout_key.getConfirmTheRecipient());//确认到账人
                customerRepairVo0.setConfirmationPaymentTime(payout_key.getConfirmationPaymentTime());//确认到账时间
                customerRepairVo0.setPaymentTime(payout_key.getPaymentTime());//客户付款时间
                customerRepairVo0.setPaymentMethod(payout_key.getPaymentMethod());//付款方式
            }
            //完成施工
//            MaterialInfo material_repari1 = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>()
//                    .eq("material_repari", customerKey));
            // 施工信息集合
            List<MaterialInfo> materialInfos = materialInfoMapper.selectList(new QueryWrapper<MaterialInfo>()
                    .eq("material_repari", customerKey).orderByAsc("create_time"));
            MaterialInfo material_repari1 = null;
            if (materialInfos.size() > 0) {
                material_repari1 = materialInfos.get(materialInfos.size() - 1);
                for (int i = 0; i < materialInfos.size(); i++) {
                    MaterialInfo materialInfo = materialInfos.get(i);
                    EvaluationBackup evaluationBackup = evaluationBackupMapper.selectOne(new QueryWrapper<EvaluationBackup>()
                            .eq("evaluation_id", customerKey).eq("material_illustrate", materialInfo.getMaterialKey()));
                    materialInfo.setEvaluationBackup(evaluationBackup);
                    if (i == materialInfos.size() - 1 && evaluationBackup != null) {
                        customerRepairVo0.setEvaluationStatus(evaluationBackup.getEvaluationStatus());
                        customerRepairVo0.setEvaluationInfo(evaluationBackup.getEvaluationInfo());
                        customerRepairVo0.setCheckAndAccept(evaluationBackup.getEvaluationFlag());
                    }
                    List<MaterialAfter> materialAfters = materialAfterMapper.selectList(new QueryWrapper<MaterialAfter>()
                            .eq("material_repari", customerKey).eq("ids",materialInfo.getMaterialKey()).select("material_after"));
                    if (materialAfters.size() > 0) {
                        materialInfo.setMaterialAfterList(materialAfters);
                    }
                    List<MaterialBefore> materialBefores = materialBeforeMapper.selectList(new QueryWrapper<MaterialBefore>()
                            .eq("material_repari", customerKey).eq("ids",materialInfo.getMaterialKey()).select("material_before"));
                    if (materialBefores.size() > 0) {
                        materialInfo.setMaterialBeforeList(materialBefores);
                    }
                }
                customerRepairVo0.setMaterialInfos(materialInfos);
            }
//            MaterialInfo material_repari1 = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>()
//                    .eq("material_repari", customerKey).orderByDesc("create_time"));
            if (material_repari1 != null) {
                if (material_repari1.getMaterialIllustrate() != null) customerRepairVo0.setMaterialIllustrate(material_repari1.getMaterialIllustrate());
                if (material_repari1.getFaultCondition() != null) customerRepairVo0.setFaultCondition(material_repari1.getFaultCondition());
                if (material_repari1.getMaterialPower() != null) customerRepairVo0.setMaterialPower(material_repari1.getMaterialPower());

                //之前的图片
//                List<MaterialBefore> materialBefores = materialBeforeMapper.selectList(new QueryWrapper<MaterialBefore>()
//                        .eq("material_repari", customerKey).select("material_before"));
//                if (materialBefores.size()!=0) customerRepairVo0.setMaterialBefore(materialBefores);
                //之后的图片
                List<MaterialAfter> materialAfters = materialAfterMapper.selectList(new QueryWrapper<MaterialAfter>()
//                        .eq("material_repari", customerKey).eq("ids","555").select("material_after"));
                        .eq("material_repari", customerKey).select("material_after"));
                if (materialAfters.size()!=0) customerRepairVo0.setMaterialAfter(materialAfters);

                /*if (material_repari1.getMaterialTime() != null) {
                    try {
                        customerRepairVo0.setMaterialTime(simpleDateFormat.parse(material_repari1.getMaterialTime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }*/
                //文字处理
                if (Objects.equals(material_repari1.getMaterialPower(), "0"))
                    customerRepairVo0.setMaterialPower("需要断电");
                if (Objects.equals(material_repari1.getMaterialPower(), "1"))
                    customerRepairVo0.setMaterialPower("无需断电");
            }
            //验收信息
            /*Evaluation evaluation_id = evaluationMapper.selectOne(new QueryWrapper<Evaluation>().eq("evaluation_id", customerKey));
            if (evaluation_id != null) {
                customerRepairVo0.setEvaluationStatus(evaluation_id.getEvaluationStatus());
                customerRepairVo0.setEvaluationInfo(evaluation_id.getEvaluationInfo());
                customerRepairVo0.setCheckAndAccept(evaluation_id.getEvaluationFlag());
            }
            //验收备份信息
            List<EvaluationBackup> evaluation_id1 = evaluationBackupMapper.selectList(new QueryWrapper<EvaluationBackup>()
                    .eq("evaluation_id", customerKey));//格局订单号去查备份行数据

            List<MaterialAfter> materialAfters = materialAfterMapper.queryByIds(customerKey);
            for (EvaluationBackup backup : evaluation_id1) {
                List<MaterialAfter> materialAfterList = new ArrayList<>();
                for (MaterialAfter materialAfter : materialAfters) {
                    if (backup.getMaterialAfter().equals(materialAfter.getIds())) {
                        materialAfterList.add(materialAfter);
                    }
                }
                backup.setMaterialAfterList(materialAfterList);
            }
            customerRepairVo0.setEvaluationBackupList(evaluation_id1);*/
            //关闭订单
            if (customerRepair.getClosingTime() != null) {
                BeanUtils.copyProperties(customerRepair, customerRepairVo0);
                SysUser sysUser2 = getSysUserByUserId(customerRepair.getClosingBy());
                customerRepairVo0.setOperator(sysUser2.getNickName());
                customerRepairVo0.setOperatorTelephone(sysUser2.getPhonenumber());
            }
            return ResultMsg.SUCCESS.setNewData(customerRepairVo0);
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("无此工单");
    }

    //角色判断
    public ArrayList<String> roleJudgment(String userId) {
        ArrayList<String> strings = new ArrayList<>();
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId).select("role_id"));
        for (SysUserRole sysUserRole : sysUserRoles) {
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614512006252556289"))) strings.add("平台客户");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510342669955074"))) strings.add("分公司经理");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510568130572289"))) strings.add("分公司运维部门负责人");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510938101739521"))) strings.add("分公司接待部门负责人");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1628948985328189441"))) strings.add("分公司财务");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614511218876837889"))) strings.add("分公司施工人员");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1623626502560641026"))) strings.add("分公司电站人员");
        }
        return strings;
    }


    public String getPersonnelPosition(Long userId) {
        Long postId = sysUserPostMapper.selectOne(new QueryWrapper<SysUserPost>().eq("user_id", userId).select("post_id")).getPostId();
        String postName = sysPostMapper.selectOne(new QueryWrapper<SysPost>().eq("post_id", postId).select("post_name")).getPostName();
        return postName;
    }
    //根据userid查询用户
    public SysUser getSysUserByUserId(String customerPlayer) {
      return   sysUserMapper.selectone(customerPlayer);
    }

    /**
     * @Author: zeh
     * 根据员工id获取公司id
     */
    public String getOrgId(String workerman) {
        SysUser sysUser = sysUserMapper.selectById(workerman);
        if (sysUser != null && sysUser.getDeptId() != null) {
            if (sysUser.getDeptId() == 1613808083627782145L) {
                return "平台客户";
            }
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            if (sysDept != null) {
                if (sysDept.getDeptType() == 1) {
                    return sysDept.getDeptName();
                }
                String[] split = sysDept.getAncestors().split(",");
                for (int i = split.length - 1; i > 1; i--) {
                    SysDept dept = sysDeptMapper.selectById(split[i]);
                    if (dept.getDeptType() == 1) {
                        return dept.getDeptName();
                    }
                }
            }
        }
        throw new ServiceException("获取人员公司信息失败");
    }

    //获取当前人的部门名字
    public String getDepartmentName(SysUser proposer) {
        SysDept sysDept = sysDeptMapper.selectById(proposer.getDeptId());
        return sysDept.getDeptName();
        /*QueryWrapper<SysDept> sysDeptQueryWrapper = new QueryWrapper<>();
        sysDeptQueryWrapper.eq("dept_id", proposer.getDeptId());
        SysDept sysDept = sysDeptMapper.selectOne(sysDeptQueryWrapper);
        String deptName = sysDept.getDeptName();
        Long parentId = sysDept.getParentId();
        QueryWrapper<SysDept> sysDeptQueryWrapper1 = new QueryWrapper<>();
        sysDeptQueryWrapper1.eq("dept_id", parentId);
        SysDept sysDept1 = sysDeptMapper.selectOne(sysDeptQueryWrapper);
        String deptName1 = sysDept1.getDeptName();
        String deptname = deptName1 + "-" + deptName;
        return deptname;*/
    }

    /**
     * @Description 接口描述 : 根据部门id查到次顶级部门名字
     * @Params * @param null
     * @Return gen
     * @Author xiaw
     * @Date 2022/12/28 11:28
     */
    public String getDeptName(String departmentId) {
        //根据部门id查次顶级部门
        String dept_id = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", departmentId)).getAncestors();
        String[] split1 = dept_id.split(",");
        //得到次顶级部门id
        String s = split1.length > 2 ? split1[2] : (split1.length > 1 ? split1[1] : departmentId);
        SysDept sysDept = sysDeptMapper.selectone(s);
        String deptName = sysDept.getDeptName();
        return deptName;
    }

    /**
     * @Description 接口描述 : 根据部门员工部门id查到次顶级公司名字
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 18:44
     */
    public SysDept getSysDeptName(Long deptId) {
        QueryWrapper<SysDept> sysDeptQueryWrapper = new QueryWrapper<>();
        sysDeptQueryWrapper.eq("dept_id", deptId);
        SysDept sysDept2 = sysDeptMapper.selectOne(sysDeptQueryWrapper);
        String avatar = sysDept2.getAncestors();
        String[] str1 = avatar.split(",");
        //获取到次顶级公司
        String gons = str1.length > 1 ? str1[1] : deptId.toString();
        QueryWrapper<SysDept> sysDeptQueryWrapper1 = new QueryWrapper<>();
        sysDeptQueryWrapper1.eq("dept_id", gons);
        SysDept sysDept3 = sysDeptMapper.selectOne(sysDeptQueryWrapper1);
        return sysDept3;
    }

    /**
     * @Description 接口描述 : 根据师傅的id去查师傅
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 18:37
     */
    public SysUser getSysUser(String player) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", player);
        SysUser sysUser1 = baseMapperUser.selectOne(queryWrapper);//师傅用户
        return sysUser1;
    }


    /**
     * @Description 接口描述 :   接单接口
     * @Params * @param null
     * customerKey : 订单的主键号码
     * customer_player  :  选择师傅ids
     * orderStatus : 修改订单状态码
     * loginmanId : 当前登录人 id
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:13
     */

    @PostMapping("updateWorkOrderStatus")
    public ResultMsg updateWorkOrderStatus(@RequestBody JSONObject jsonObject) {
        if (jsonObject == null || StringUtils.isBlank(jsonObject.getString("customerKey")) || jsonObject.getInteger("orderStatus") == null) {
            return ResultMsg.ARGS_ERROR;
        }
        ResultMsg i = iCustomerRepairService.updateWorkOrderStatus(jsonObject);
        return ResultMsg.SUCCESS.setNewData(i);
    }

}
